package com.seata.orderseata.service.impl;

import com.seata.orderseata.domain.User;
import com.seata.orderseata.mapper.UserMapper;
import com.seata.orderseata.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author business
 * @since 2023-04-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Map saveUser(User user) {

        Map map = new HashMap<>();
        if (save(user)) {
            //调用stock_seata
            List<ServiceInstance> instances = discoveryClient.getInstances("stock");
            ServiceInstance serviceInstance = instances.get(0);
            URI uri = serviceInstance.getUri();
            String tageUrl = uri + "/user/saveStockUser";

            map = restTemplate.postForObject(tageUrl, user, Map.class);
        }
        return map;
    }
}
